/*
 *
 *  Copyright (C) 2009 LibreSoft
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *
 *  Author : Roberto Calvo Palomino <rocapal@gsyc.es>
 *
 */

package com.LibreGeoSocial.App;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.LibreGeoSocial.Api.LibreGeoSocial;
import com.LibreGeoSocial.Api.Photo;
import com.LibreGeoSocial.App.Utils.BitmapUtils;




public class UploadPhoto extends Activity implements OnClickListener {

	static Button btTakePhoto;
	static Button btSelectPicture;
	static Button btUpload;
	static Button btPrivacy;

	static TextView txtDescription;
	static TextView txtTitle;
	static ImageView imgPhoto;
	
	static String strImagePath = null; 
	
	private static final int REQUEST_CAMERA = 1;
	private static final int REQUEST_SELECT_PHOTO = 2;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera);
        
        btSelectPicture = (Button)this.findViewById(R.id.btSelectPicture); 
        btSelectPicture.setOnClickListener(this);
        
        btUpload = (Button)this.findViewById(R.id.btUpload); 
        btUpload.setOnClickListener(this);
        
        btPrivacy = (Button)this.findViewById(R.id.btPrivacy); 
        btPrivacy.setOnClickListener(this);
        
        imgPhoto = (ImageView) this.findViewById(R.id.imgPhoto);
 
        
        txtDescription = (TextView)this.findViewById(R.id.txtComment);
        
        txtTitle = (TextView)this.findViewById(R.id.txtTitle);
        
    }
    
    
    public static boolean isSdPresent() 
    {
    	return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }


	public void onClick(View arg0) {

		
		if (btPrivacy.isPressed())
		{
			Intent i = new Intent(this,LGS_Preferences.class);
			startActivity(i);
		}    	
		else if (btSelectPicture.isPressed())
		{
			doSelectImage();			
			
		}
		else if (btUpload.isPressed())
		{
						 						
			Photo myPhoto = new Photo(0,
							Home.currentLocation.getLatitude(),
							Home.currentLocation.getLongitude(),
							Home.currentLocation.getAltitude(),
							0.0,
							txtTitle.getText().toString(),
							txtDescription.getText().toString(),
							strImagePath,
							null,
							null);
			
			if ( LibreGeoSocial.getInstance().uploadPhoto(myPhoto) )
			{
				
				// Get the photo privacy
				
                // User text   
        	    SharedPreferences sharedPreferences = 
        	    	PreferenceManager.getDefaultSharedPreferences(getBaseContext());

        		// Update state in twitter
        		String photoPrivacy = 
        			sharedPreferences.getString (LGS_Preferences.KEY_APP_PHOTO_PRIVACY, "friends");
				
				// Get the photo id
				Integer id = LibreGeoSocial.getInstance().getLastId();
					
				if ( LibreGeoSocial.getInstance().setPrivacyNode (id, LibreGeoSocial.getInstance().PRIVACY_FRIENDS,true))
				
	        		Toast.makeText(getBaseContext(), 
	  					   "Upload photo correctly!!", 
	  					   Toast.LENGTH_LONG).show();
				
				else
					
					Toast.makeText(getBaseContext(), 
		  					   "The photo was upload correctly, but there is a problem with the privacy!", 
		  					   Toast.LENGTH_LONG).show();
					
			}
			else
			{
        		Toast.makeText(getBaseContext(), 
  					   "Upload photo error: " + 
  					   LibreGeoSocial.getInstance().getLastMsgServer(), 
  					   Toast.LENGTH_LONG).show();
			}
		}
	}
	
    private void doCaptureImage() {
    	Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
    	startActivityForResult(i,REQUEST_CAMERA);
    }
    
   
    
	private void doSelectImage() {
		
    	Intent i = new Intent(Intent.ACTION_PICK) ;
    	i.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
    					 MediaStore.Images.Media.CONTENT_TYPE) ;
    	
    	startActivityForResult(i,REQUEST_SELECT_PHOTO) ;
    }
	

	protected void onActivityResult (int requestCode, int resultCode, Intent data) { 
		
		switch (requestCode) { 
		
	    	case REQUEST_CAMERA:
	    		
	    		if( resultCode != 0 ) {
		    		Bundle extras = data.getExtras();
		    		Bitmap bmp = (Bitmap)extras.get("data") ;
		    		
		    		if( bmp != null ) {
		    			String fileName = "/sdcard/dcim/Camera/ping_media.jpg"; 
		    			File f = new File(fileName); 
		    			if( f.exists() ) f.delete(); 
		    			
						try {
							FileOutputStream out = new FileOutputStream(fileName);
			    			bmp.compress(CompressFormat.JPEG, 12, out) ;
			    			out.close() ;
			    			String media_path = f.getAbsolutePath() ;
			    			
			    			Log.d("LibreGeoSocial","onActivityResult("+requestCode+","+resultCode+","+media_path+")") ;
						
						} catch (FileNotFoundException e) {
							Log.e("LibreGeoSocial","FileNotFoundException generated when using camera") ;
						
						} catch (IOException e) {
							Log.e("LibreGeoSocial","IOException generated when using camera") ;
						}
		    		}
	    		}
	    		break;
    		
	    	case REQUEST_SELECT_PHOTO:
	    		
	    		if( resultCode != 0 ) {
	    			
		    		Cursor c = managedQuery(data.getData(),null,null,null,null) ;
		    		
		    		if( c.moveToFirst() ) {
		    		
		    			String media_path = c.getString(1) ;
		    			
		    			Log.d("LibreGeoSocial","onActivityResult("+requestCode+","+resultCode+","+media_path+")") ;
		    					    			
		    			strImagePath = media_path;
		    			
		    			Bitmap photo = BitmapUtils.loadBitMapFromFile(strImagePath);
		    			
		    			imgPhoto.setImageBitmap(photo);
		    		}		    		
	    		} 
	    		
	    		break;
	
            default:
                break; 
		}
	}

}
